from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.pool import QueuePool

from config import appSettings

# SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
SQLALCHEMY_DATABASE_URL = (
    f"mysql+pymysql://{appSettings.db_user}:{appSettings.db_password}@{appSettings.db_host}:"
    f"{appSettings.db_port}/{appSettings.db_database}"
)
print(SQLALCHEMY_DATABASE_URL)
engine = create_engine(
    SQLALCHEMY_DATABASE_URL,
    pool_size=5,
    pool_timeout=30,
    pool_pre_ping=True,
    pool_recycle=3600,
    poolclass=QueuePool,
)
SessionLocal = sessionmaker(
    autocommit=False,
    autoflush=False,
    bind=engine,
    expire_on_commit=False,
)
Session = scoped_session(SessionLocal)
Base = declarative_base()

Base.metadata.create_all(bind=engine)


# Dependency
def get_db():
    db = Session()
    try:
        yield db
    finally:
        db.close()
